<template>
    <div class="login-wrapper">
        <div class="login">

            <el-button 
                type="danger" 
                size="small" 
                circle 
                style="position: absolute; right: 5px; top: 5px; font-size: 16px;"
                @click="$emit('close')"
            >
                <el-icon><Close /></el-icon>
            </el-button>
            
            <el-form 
                :rules="rules"
                :model="formData"
            >
                <el-form-item label="username" prop="username">
                    <el-input 
                        v-model="formData.username" 
                        style="width: 320px"
                        placeholder="用户名"
                    />
                </el-form-item>

                <el-form-item label="password" prop="password">
                    <el-input 
                        v-model="formData.password" 
                        style="width: 320px;"
                        type="password"
                        show-password
                        placeholder="密码"
                    />
                </el-form-item>

                <el-form-item>
                    <el-button type="primary" style="margin-left: auto; margin-top: 10px;">注册</el-button>
                    <el-button type="primary" style="margin-right: auto; margin-top: 10px;" @click="submit()">登录</el-button>
                </el-form-item>
            </el-form>
        </div>
    </div>
</template>

<script>
import { Close } from '@element-plus/icons-vue'
import { login } from '@/api/user.js'

export default {
    name: 'Login',
    components: {
        Close
    },
    data () {
        return {
            formData: {
                username: '',
                password: ''
            },
            rules: {
                username:[
                    { required: true, message: '用户名不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
                password:[
                    { required: true, message: '密码不能为空', trigger: 'blur' },
                    { max: 64, message: '最大长度为64', trigger: 'blur' },
                ],
            }
        }
    },

    methods: {
        async submit () {
            let result = await login(this.formData)
            if (result instanceof Error) ElMessage.error(result.message)

            this.$store.state.user = result
            ElMessage.success('登录成功')
            this.$emit('close')
        }
    }
}
</script>

<style lang="less" scoped>
.login-wrapper{
    position: fixed;
    top: 0;
    right: 0;
    bottom: 0;
    left: 0;
    z-index: 999;
    background-color: rgba(0,0,0,.5);

    .login{
        padding: 30px 30px 10px;
        background-color: #fff;
        border-radius: 10px;
        position: absolute;
        left: 50%;
        top: 50%;
        transform: translateX(-50%) translateY(-50%);
    }
}
</style>